package component.controls.loader
{
	import component.controls.interfaces.IDispose;
	import component.global.manager.EventMgr;
	
	import flash.display.Loader;
	import flash.events.Event;
	import flash.events.HTTPStatusEvent;
	import flash.events.IOErrorEvent;
	import flash.events.ProgressEvent;
	import flash.net.URLRequest;
	import flash.net.URLRequestMethod;
	import flash.net.URLVariables;
	import flash.system.LoaderContext;
	
	public class BitmapLoader extends BaseLoader implements IDispose
	{
		public function BitmapLoader(url:String, context:LoaderContext = null, variables:URLVariables=null, method:String=URLRequestMethod.GET)
		{
			_context = context;
			super(url, variables, method);
		}
		
		protected var _context:LoaderContext;
		
		override protected function initLoader():void{
			_loader = new Loader();
			EventMgr.Instance.addEvent(_loader.contentLoaderInfo, [Event.COMPLETE,HTTPStatusEvent.HTTP_STATUS,ProgressEvent.PROGRESS,IOErrorEvent.IO_ERROR],[__onComplete,__onHTTPStatus,__onProgress,__onIOError]);
		}
		
		override public function get content():*{
			return _loader;	
		}
		
		override public function load(url:String = null):void{
			_isLoading = true;
			if(url)_url = url;
			if(!_url){
				_isComplete = true;
				_isLoading = false;
				_errorMessage = "url cannot be null!";
				dispatch(LoaderEvent.ERROR);
				dispatch(LoaderEvent.COMPLETE);
				return;
			}
			_request = new URLRequest(_url + "?random=" + Math.floor(Math.random()* 9999));
			_request.method = _requestMethod;
			_request.data = _urlVariables;
			_loader.load(_request, _context);
		}
		
		override protected function __onComplete(e:Event):void{
			_isComplete = true;
			_isLoading = false;
			if(_completeFunc != null)_completeFunc(content);
			dispatch(LoaderEvent.PROGRESS);
			dispatch(LoaderEvent.COMPLETE);
			EventMgr.Instance.removeEvent(_loader.contentLoaderInfo, [Event.COMPLETE,HTTPStatusEvent.HTTP_STATUS,ProgressEvent.PROGRESS,IOErrorEvent.IO_ERROR],[__onComplete,__onHTTPStatus,__onProgress,__onIOError]);
		}
		
		override protected function __onProgress(e:ProgressEvent):void{
			_progress = Math.round(100 * (_loader.contentLoaderInfo.bytesLoaded / _loader.contentLoaderInfo.bytesTotal ));
			dispatch(LoaderEvent.PROGRESS);
		}
	}
}